package controller

import (
	"encoding/json"
	"gin_demo/common"
	"gin_demo/model"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"log"
	"net/http"
)

func Register(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	//PortForm 是html form表单post 使用的方式
	//name := ctx.PostForm("name")
	//password := ctx.PostForm("password")

	// Vue this.$http.Post()方式
	var userParam model.UserParam
	if err := json.NewDecoder(ctx.Request.Body).Decode(&userParam); err != nil{
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":"请求错误",
		})
	}
	//数据验证
	if len(userParam.Name) == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "用户名为空",
		})
		log.Println("name为空")
		return
	}
	if len(userParam.Password) == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg": "password为空",
		})
		log.Println("password为空")
		return
	}

	//判断用户名是否存在
	if isNameExist(DB, userParam.Name){
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg": "用户已经存在",
		})
		return
	}
	//创建用户
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(userParam.Password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg": "加密错误",
		})
		return
	}
	newUser := model.User{
		Name: userParam.Name,
		Password: string(hashedPassword),
	}
	DB.Create(&newUser)
	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"message": "注册成功",
	})
}

func Login(ctx *gin.Context){
	//获取参数
	var userParam model.UserParam
	if err := json.NewDecoder(ctx.Request.Body).Decode(&userParam); err != nil{
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":"请求错误",
		})
	}
	//数据验证
	if len(userParam.Password) == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg": "password为空",
		})
		log.Println("password为空")
		return
		}
		if len(userParam.Name) == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg": "用户名为空",
		})
		log.Println("name为空")
		return
	}
	//判断密码是否正确
	db := common.GetDB()
	var user model.User
	db.Where("name = ?", userParam.Name).First(&user)
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(userParam.Password)); err != nil{
		ctx.JSON(http.StatusBadRequest, gin.H{"code" : 400, "msg" : "密码错误"})
	}
	//密码验证成功发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常分配token失败"})
		log.Printf("Token 生成失败 : %v", err)
		return
	}

	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{"token": token},
		"msg": "登录成功",
	})

}

func Info(ctx *gin.Context){
	user, _ := ctx.Get("user")
	ctx.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{"user": user}})
}

func isNameExist(db *gorm.DB, name string) bool{
	var user model.User
	db.Where("name = ?", name).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}